import { createServer } from 'http';
import { readFile } from 'fs/promises';
import { resolve, extname } from 'path';

const mimeTypes = {
    '.html': 'text/html',
    '.js': 'application/javascript',
    '.css': 'text/css',
    '.json': 'application/json',
    '.png': 'image/png',
    '.jpg': 'image/jpeg',
    '.svg': 'image/svg+xml',
};

const server = createServer(async (req, res) => {
    try {
        let url = req.url === '/' ? '/index.html' : req.url;
        const filePath = resolve(process.cwd(), `.${url}`);
        const ext = extname(filePath);
        const content = await readFile(filePath, 'utf-8');

        if (ext === '.js') {
            // Basic ES Module transformation
            res.writeHead(200, { 'Content-Type': mimeTypes[ext] });
            res.end(content.replace(/process\.env\.NODE_ENV/g, '"development"'));
        } else {
            res.writeHead(200, { 'Content-Type': mimeTypes[ext] || 'text/plain' });
            res.end(content);
        }
    } catch (err) {
        res.writeHead(404, { 'Content-Type': 'text/plain' });
        res.end('Not Found');
    }
});

server.listen(3000, () => {
    console.log('Vite-like dev server running at http://localhost:3000');
});